﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Vivasky.Labs.Utils
{
	public class FileUtils
	{
		/// <summary>
		/// 删除文件夹。
		/// </summary>
		/// <param name="dir"></param>
		public static void DeleteFolder(string dir)
		{
			Directory.GetFileSystemEntries(dir).ToList().ForEach(item =>
			{
				if (File.Exists(item))
				{
					FileInfo fi = new FileInfo(item);
					if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
						fi.Attributes = FileAttributes.Normal;
					File.Delete(item);//直接删除其中的文件   
				}
				else
					DeleteFolder(item);//递归删除子文件夹 
			});
			Directory.Delete(dir);//删除已空文件夹   
		}
		/// <summary>
		/// 删除指定文件夹中指定的文件夹。
		/// </summary>
		/// <param name="folderNames"></param>
		/// <param name="dir"></param>
		public static List<DirectoryInfo> DeleteFolder(List<string> folderNames, string dir, out List<DirectoryInfo> failedFolders)
		{
			var  root = new DirectoryInfo(dir);
			var  deletingFolders = new List<DirectoryInfo>();
			var _failedFolders = new List<DirectoryInfo>();
			var _okFolders = new List<DirectoryInfo>();
			folderNames.ForEach(folder =>
			{
				deletingFolders.AddRange(root.GetDirectories(folder, SearchOption.AllDirectories));
			});
			deletingFolders.ForEach(obj =>
			{
				try
				{
					DeleteFolder(obj.FullName);
					_okFolders.Add(obj);
				}
				catch
				{
					_failedFolders.Add(obj);
				}
			});
			failedFolders = _failedFolders;
			return _okFolders;
		}// /DeleteFolder
		
	}
}
